<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  videoSrc: {
    type: String,
    required: true
  },
  poster: {
    type: String,
    default: '/images/poster.svg'
  },
  isLoading: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['loaded', 'error'])
const hasError = ref(false)
const errorMessage = ref('')
const videoElement = ref(null)
const isPlaying = ref(false)

// 备用视频源 - 使用公开可访问的测试视频
const fallbackSources = [
  'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/1080/Big_Buck_Bunny_1080_10s_1MB.mp4',
  'https://test-videos.co.uk/vids/jellyfish/mp4/h264/720/Jellyfish_720_10s_1MB.mp4'
]

let currentFallbackIndex = 0
let isUsingFallback = false

function handleVideoLoaded() {
  hasError.value = false
  emit('loaded')
}

function handleVideoError(event) {
  console.error('视频加载错误:', event.target.error)
  hasError.value = true
  isLoading.value = false
  
  if (!isUsingFallback && currentFallbackIndex < fallbackSources.length) {
    // 尝试使用备用视频源
    isUsingFallback = true
    event.target.src = fallbackSources[currentFallbackIndex]
    currentFallbackIndex++
    hasError.value = false
    isLoading.value = true
    event.target.load()
    errorMessage.value = '尝试切换视频源...'
    console.log('尝试备用视频源:', event.target.src)
  } else {
    errorMessage.value = '视频加载失败，请稍后再试'
    emit('error', event.target.error)
  }
}

function handleVideoPlay() {
  isPlaying.value = true
}

function handleVideoPause() {
  isPlaying.value = false
}

function handleVideoStalled() {
  console.warn('视频加载停滞，尝试重新加载...')
  if (videoElement.value) {
    videoElement.value.load()
  }
}

function retryPlay() {
  hasError.value = false
  isLoading.value = true
  currentFallbackIndex = 0
  isUsingFallback = false
  
  if (videoElement.value) {
    videoElement.value.src = props.videoSrc
    videoElement.value.load()
  }
}

watch(() => props.videoSrc, (newSrc) => {
  if (videoElement.value) {
    hasError.value = false
    isLoading.value = true
    currentFallbackIndex = 0
    isUsingFallback = false
    videoElement.value.src = newSrc
    videoElement.value.load()
  }
})

onMounted(() => {
  // 添加事件监听器，确保视频元素正确初始化
  if (videoElement.value) {
    videoElement.value.addEventListener('loadeddata', handleVideoLoaded)
    videoElement.value.addEventListener('error', handleVideoError)
    videoElement.value.addEventListener('play', handleVideoPlay)
    videoElement.value.addEventListener('pause', handleVideoPause)
    videoElement.value.addEventListener('stalled', handleVideoStalled)
    
    // 初始化时预加载视频
    videoElement.value.preload = 'metadata'
  }
})
</script>

<template>
  <div class="player-container">
    <div class="player-wrap">
      <!-- 错误状态显示 -->
      <div v-if="hasError" class="error-overlay">
        <div class="error-content">
          <div class="error-icon">⚠️</div>
          <p class="error-message">{{ errorMessage }}</p>
          <button class="retry-button" @click="retryPlay">重新加载</button>
        </div>
      </div>
      
      <!-- 视频播放器 -->
      <video
        ref="videoElement"
        class="player"
        :src="videoSrc"
        controls
        controlsList="nodownload"
        preload="metadata"
        :poster="poster"
        @loadeddata="handleVideoLoaded"
        @error="handleVideoError"
        @play="handleVideoPlay"
        @pause="handleVideoPause"
        @stalled="handleVideoStalled"
      ></video>
      
      <!-- 加载动画 -->
      <div v-if="isLoading && !hasError" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p class="loading-text">视频加载中...</p>
      </div>
      
      <!-- 提示信息 -->
      <div v-if="isUsingFallback && !hasError" class="fallback-notice">
        <p>正在使用备用视频源</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 播放器容器 */
.player-container {
  margin-bottom: 24px;
  position: relative;
}

.player-wrap {
  border-radius: var(--radius-lg);
  overflow: hidden;
  border: 1px solid var(--border);
  background: var(--surface);
  box-shadow: var(--shadow-lg), 0 0 30px rgba(99, 102, 241, 0.05);
  position: relative;
}

.player {
  width: 100%;
  height: auto;
  display: block;
  aspect-ratio: 16 / 9;
  transition: opacity 0.3s ease;
}

/* 加载动画 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
  gap: 16px;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 3px solid rgba(99, 102, 241, 0.2);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  box-shadow: 0 0 20px rgba(99, 102, 241, 0.3);
}

.loading-text {
  color: var(--text);
  font-size: 16px;
  font-weight: 500;
}

/* 错误状态样式 */
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
  gap: 16px;
  padding: 24px;
  text-align: center;
}

.error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  max-width: 400px;
}

.error-icon {
  font-size: 48px;
}

.error-message {
  color: var(--error);
  font-size: 16px;
  line-height: 1.5;
}

.retry-button {
  padding: 12px 24px;
  background-color: var(--accent);
  color: white;
  border: none;
  border-radius: var(--radius-md);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.retry-button:hover {
  background-color: var(--accent-dark);
}

/* 备用源提示 */
.fallback-notice {
  position: absolute;
  top: 16px;
  right: 16px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: var(--radius-sm);
  font-size: 12px;
  z-index: 5;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>